package net.lcqf.websocket.server;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;

import java.util.List;

/**
 * 消息编码器（发送数据到Unity）
 * +----------------------------------------------------------------------
 * // | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * // +----------------------------------------------------------------------
 * // | Copyright (c) 2021-2025 聊来 All rights reserved.
 * // +----------------------------------------------------------------------
 * // | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * // +----------------------------------------------------------------------
 * // | @Author: 聊来 <18970881148@qq.com>
 * // +----------------------------------------------------------------------
 * // | DateTime: 2025/4/15 21:10
 * // +----------------------------------------------------------------------
 */

public class ProtobufEncoder extends MessageToMessageEncoder<MsgInfoPojo.MsgInfo> {

    @Override
    protected void encode(ChannelHandlerContext ctx, MsgInfoPojo.MsgInfo msgInfo, List<Object> out) throws Exception {
        ByteBuf buffer = ByteBufAllocator.DEFAULT.buffer();
        byte[] protobufData = msgInfo.toByteArray();

        // 添加大端前缀
        buffer.writeInt(protobufData.length);
        buffer.writeBytes(protobufData);

        out.add(new BinaryWebSocketFrame(buffer));

    }
}
